package com.cherrypt.api.core.util;

import com.cherrypt.api.common.enums.PostInfoTypeEnum;
import com.cherrypt.api.common.util.RegexUtils;
import com.cherrypt.api.model.dataobject.PostInfo;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PostInfoUtils {
    private static final Logger logger = LoggerFactory.getLogger(PostInfoUtils.class);

    public static PostInfo getPostInfoByImdb(JsonNode rootNode) {
        PostInfo postInfo = new PostInfo();
        postInfo.setInfoId(Long.valueOf(rootNode.get("imdbID").asText().replaceFirst("tt", "")));
        postInfo.setSummary(rootNode.get("Plot").asText());
        postInfo.setImage(rootNode.get("Poster").asText());
        postInfo.setType(PostInfoTypeEnum.IMDB.getType());
        postInfo.setRatingAverage(Float.valueOf(rootNode.get("imdbRating").asText()));
        postInfo.setRatingNumRaters(Integer.valueOf(rootNode.get("imdbVotes").asText().replaceAll(",", "")));
        postInfo.setContent(rootNode.toString());
        return postInfo;
    }

    public static PostInfo getPostInfoByDouban(JsonNode rootNode, PostInfoTypeEnum postInfoTypeEnum) {
        PostInfo postInfo = new PostInfo();
        postInfo.setInfoId(Long.valueOf(RegexUtils.getMatches("\\d+", rootNode.get("id").asText()).iterator().next()));
        // get image
        JsonNode imageNode = rootNode.get("image");
        JsonNode imagesNode = rootNode.get("images");
        if (imageNode != null && StringUtils.isNotBlank(imageNode.asText())) {
            postInfo.setImage(imageNode.asText());
        } else if (imagesNode != null && StringUtils.isNotBlank(imagesNode.get(0).asText())) {
            postInfo.setImage(imagesNode.get(0).asText());
        }
        // get summary
        JsonNode summaryNode = rootNode.get("summary");
        if (summaryNode != null && StringUtils.isNotBlank(summaryNode.asText())) {
            postInfo.setSummary(summaryNode.asText());
        }
        postInfo.setType(postInfoTypeEnum.getType());
        JsonNode ratingNode = rootNode.get("rating");
        JsonNode averageNode = ratingNode.get("average");
        if (averageNode != null && StringUtils.isNotBlank(averageNode.asText())) {
            postInfo.setRatingAverage(Float.valueOf(averageNode.asText()));
        } else {
            postInfo.setRatingAverage(0F);
        }
        JsonNode numRatersNode = ratingNode.get("numRaters");
        if (numRatersNode != null) {
            postInfo.setRatingNumRaters(numRatersNode.asInt());
        } else {
            postInfo.setRatingNumRaters(0);
        }
        postInfo.setContent(rootNode.toString());
        return postInfo;
    }
}
